package com.atguigu.tingshu.search.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author caesar
 * @project-name:tingshu-server
 * @date 2025/10/27 18:03:34
 * @description: 接收端方法
 * @apiNote：
 */
public class SearchReceiver {
    @Autowired
    private SearchService searchService;

    /**
     * MQ实现专辑上架
     * @param albumId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER, durable = "true"),
            key = {MqConst.ROUTING_ALBUM_UPPER}
    ))
    public void upper_album(Long albumId, Message message, Channel channel) {
        if(albumId != null) {
            searchService.upperAlbum(albumId);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    /**
     * 专辑下架
     * @param albumId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_ALBUM_LOWER, durable = "true"),
            key = {MqConst.ROUTING_ALBUM_LOWER}
    ))
    public void lowerGoods(Long albumId, Message message, Channel channel) {
        //业务处理，专辑id不为空，就执行下架方法（删除ES中数据）
        if (null != albumId) {
            searchService.lowerAlbum(albumId);
        }

        //手动应答，参数1：每条传递给消费者的唯一标识符
        // 参数2：是否批量确认之前的所有未确认消息。
        //如果设置为 false：只确认当前这一条消息。
        //如果设置为 true：则会确认所有小于等于当前 delivery tag 的消息（即一次确认多条）。
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
